﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _1Dot9MasterBiz;
using _1Dot9MasterCommon;

public partial class Admin_GalleryItemReg : AdminBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        init();
    }

    /// <summary>
    /// 확인 버튼 클릭 이벤트
    /// </summary>    
    protected void ibtnConfirm_Click(object sender, ImageClickEventArgs e)
    {
        if (!SaveValidation())
            return;

        if (WorkItemResisteration())
        {
            Response.Write("<script>parent.PopClose();</script>");
        }
        
        //this.Response.Redirect(this.Page.Request.Url.ToString());
    }

    /// <summary>
    /// 취소 버튼 클릭 이벤트
    /// </summary>
    protected void ibtnCancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Write("<script>parent.PopClose();</script>");
    }

    /// <summary>
    /// 파일 및 DB 저장 함수 함수
    /// </summary>
    public bool WorkItemResisteration()
    {
        try
        {
            string guId = Utils.GetGuid();
            string ext = Utils.GetExtension(iconUpload.FileName);
            string fileNm = guId + ext;

            //아이콘 이미지 업로드
            if (!IconUpload(fileNm))
            {
                Response.Write("<script> alert('아이콘 등록 실패'); </script>");
                return false;
            }
            
            //파일 이미지 업로드
            if (!ImgUpload(fileNm))
            {
                Response.Write("<script> alert('이미지 등록 실패'); </script>");
                return false;
            }

            //DB Insert
            if (SetWorkItem(guId, ext, txtTitle.Text, txtMemo.Text, rdoListType.SelectedValue, true) < 1)
            {
                Response.Write("<script> alert('DB 등록 실패'); </script>");
                return false;
            }

            Response.Write("<script> alert('등록 되었습니다.'); </script>");
            return true;
        }
        catch (Exception ex)
        {
            Response.Write("<script> alert('" + ex.Message.ToString() + "'); </script>");
            return false;
        }
    }

    #region WorkItem DB 등록
    /// <summary>
    /// WorkItem DB 등록
    /// </summary>
    protected int SetWorkItem(string _guid, string _extention, string _title, string _note, string _type, bool _useYn)
    {
        int result = 0;
        try
        {
            using (WorkBiz workBiz = new WorkBiz())
            {
                Hashtable htParams = new Hashtable();

                htParams.Add("@P_GUID", _guid);
                htParams.Add("@P_EXTENTION", _extention);
                htParams.Add("@P_TITLE", _title);
                htParams.Add("@P_NOTE", _note);
                htParams.Add("@P_TYPE", _type);
                htParams.Add("@P_USE_YN", _useYn);

                result = workBiz.SetWorkItem(htParams);
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script> alert('" + ex.Message.ToString() + "'); </script>");
        }

        return result;
    }
    #endregion

    #region 이미지 파일 업로드
    /// <summary>
    ///  아이콘 이미지 서버 write
    /// </summary>    
    protected bool IconUpload(string _fimeNm)
    {
        int UploadedLength = 0;
        int ContentLength = this.iconUpload.PostedFile.ContentLength;

        string path = this.Server.MapPath(@"~/Files/icons");
        string fileName = _fimeNm;

        int bufferSize = 1;
        byte[] buffer = new byte[bufferSize];

        try
        {
            using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                while (UploadedLength < ContentLength)
                {
                    //Fill the buffer from the input stream
                    int bytes = this.iconUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);

                    //Writing the bytes to the file stream
                    fs.Write(buffer, 0, bytes);
                    UploadedLength += bytes;
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "');</script>");
            return false;
        }
    }

    /// <summary>
    /// 이미지 서버 업로드
    /// </summary>    
    protected bool ImgUpload(string _fimeNm)
    {
        int UploadedLength = 0;
        int ContentLength = this.imgUpload.PostedFile.ContentLength;

        string path = this.Server.MapPath(@"~/Files");
        string fileName = _fimeNm;

        int bufferSize = 1;
        byte[] buffer = new byte[bufferSize];

        try
        {
            using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                while (UploadedLength < ContentLength)
                {
                    //Fill the buffer from the input stream
                    int bytes = this.imgUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);

                    //Writing the bytes to the file stream
                    fs.Write(buffer, 0, bytes);
                    UploadedLength += bytes;
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "');</script>");
            return false;
        }
    }
    #endregion

    protected bool SaveValidation()
    {
        if (txtTitle.Text.Trim().Length < 1)
        {
            Response.Write("<script>alert('제목을 입력하세요');</script>");
            return false;
        }

        if ((null == iconUpload.PostedFile) || (0 >= iconUpload.PostedFile.ContentLength))
        {
            Response.Write("<script>alert('이미지를 아이콘을 선택하세요');</script>");
            return false;
        }

        if ((null == imgUpload.PostedFile) || (0 >= imgUpload.PostedFile.ContentLength))
        {
            Response.Write("<script>alert('이미지를 선택하세요');</script>");
            return false;
        }

        return true;
    }
}